package com.edu.edu.day9_19_week7_homework.activity;

import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.edu.edu.day9_19_week7_homework.R;
import com.edu.edu.day9_19_week7_homework.SQLite.DBHelpter;
import com.edu.edu.day9_19_week7_homework.service.DownVideoService;
import com.edu.edu.day9_19_week7_homework.utils.SDUtil;

import java.io.File;

/**
 * Created by Administrator on 9/19 0019.
 */
public class DetailActivity extends AppCompatActivity{

    private VideoView mVideo;
    private TextView mCaption;
    private Button mCollect;
    private SQLiteDatabase mDb;
    private DBHelpter dbHelpter;
    private String caption;
    private String video;
    private LoadVideoBroadReceiver mReceiver;
    private Button mDownVideo;
    private Toolbar mToolbar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);//关联详情页面布局
        initView();//初始化控件
        initData();//初始化数据
        mReceiver = new LoadVideoBroadReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("succedd");
        //注册广播

        registerReceiver(mReceiver,filter);
    }

    private void startVideo(String str) {
        //视频网址
        mVideo.setMediaController(new MediaController(this));//添加进度条
        mVideo.setVideoURI(Uri.parse(str));
        //设置屏幕方向->横屏
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        //开始播放视频
        mVideo.start();
    }

    private void initData() {
        Intent intent = getIntent();
        //根据相应的key获取标题和url
        caption = intent.getStringExtra("caption");
        video = intent.getStringExtra("video");
        //设置text内容
        mCaption.setText(caption);
        startVideo(video);//播放视频
    }

    private void initView() {
        mVideo = (VideoView) findViewById(R.id.detail_video);
        mCaption = (TextView) findViewById(R.id.detail_text);
        mCollect = (Button) findViewById(R.id.detail_collect);
        mDownVideo = (Button) findViewById(R.id.detail_downVideo);
        mToolbar = (Toolbar) findViewById(R.id.detail_toolbar);
        //数据库初始化
        dbHelpter = new DBHelpter(this);
        mDb = dbHelpter.getWritableDatabase();



        //Toolbar的home按钮点击事件
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //点击按钮直接销毁当前activity，回到父activity
                finish();
            }
        });

        //下载视频的监听
        mDownVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(DetailActivity.this,"正在下载中...",Toast.LENGTH_LONG).show();
                Intent intent = new Intent(DetailActivity.this, DownVideoService.class);
                //开启服务，发送网址过去
                intent.putExtra("aaa",video);
                startService(intent);
            }
        });
    }

    //点击收藏按钮收藏文字
    public void collect(View view) {
        String nameStr = returnQurey();
        //判断是否已收藏
        if (caption.equals(nameStr)) {
            Toast.makeText(DetailActivity.this,"已收藏",Toast.LENGTH_LONG).show();
        }else{
            //存储数据
            ContentValues values = new ContentValues();
            values.put("name",caption);
            values.put("url", video);
            long id = mDb.insert("food", null, values);
            if(id > 0){
                Toast.makeText(DetailActivity.this, "收藏成功", Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(DetailActivity.this, "收藏失败", Toast.LENGTH_SHORT).show();
            }
        }
    }
    //根据获取的caption查询数据库返回游标集合，然后遍历
    public String returnQurey() {
        String nameStr = null;
        Cursor cursor = mDb.query("food", new String[]{"name"}, "name=?", new String[]{caption}, null, null, null);
        if (cursor == null) {
            return null;
        } else {
            while (cursor.moveToNext()) {
                //根据列名获取字段号
                int nameid = cursor.getColumnIndex("name");
                //根据字段号获取对应的值
                nameStr = cursor.getString(nameid);
            }
            cursor.close();
        }
        return nameStr;
    }
    //注册广播
    @Override
    protected void onStart() {
        super.onStart();

    }

    //取消注册广播
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mReceiver != null){
            unregisterReceiver(mReceiver);
        }
    }

    class LoadVideoBroadReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            String wan = intent.getStringExtra("wan");
            if("succedd".equals(action) && wan != null){
                Toast.makeText(DetailActivity.this,wan,Toast.LENGTH_LONG).show();
                byte[] bytes = SDUtil.readData(video);
                Log.i("TAG","detailactivity>>>>>>>>>>>>" + video);
                if (bytes != null){
                    String path = SDUtil.getSDPath() + File.separator + SDUtil.STORAGE_PATH+ File.separator + video ;
                    Log.i("TAG","detailactivity>>>>>>>>>>>>" + path);
//                    startVideo(path);
                }
            }
        }
    }
}
